#include "LoopThreadPool.hpp"
#include "Acceptor.hpp"
#include "Connection.hpp"
#include <signal.h>

class TcpServer
{
private:
    int _port;
    uint64_t _next_id;                                  // 一个自动增长的连接ID
    int _timeout;                                       // 非活跃连接的统计时间
    bool _enable_inactive_release;                      // 是否启动非活跃连接超时销毁
    EventLoop _baseloop;                                // 主线程EventLoop对象，负责监听事件的处理
    Acceptor _acceptor;                                 // 监听套接字管理对象
    LoopThreadPool _pool;                               // 从属EventLoop线程池
    std::unordered_map<uint64_t, PtrConnection> _conns; // 管理所有连接对应的shared_ptr对象

    using ConnectionCallback = std::function<void(const PtrConnection &)>;
    using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
    using CloseCallback = std::function<void(const PtrConnection &)>;
    using AnyEventCallback = std::function<void(const PtrConnection &)>;
    ConnectionCallback _connection_callback;
    MessageCallback _message_callback;
    CloseCallback _closed_callback;
    AnyEventCallback _anyevent_callback;

private:
    // 为新连接构造一个Connection进行管理
    void NewConnection(int fd)
    {
        _next_id++;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
        conn->SetMessageCallback(_message_callback);
        conn->SetCloseCallback(_closed_callback);
        conn->SetConnectionCallback(_connection_callback);
        conn->SetAnyEventCallback(_anyevent_callback);
        conn->SetSvrCloseCallback(std::bind(&TcpServer::RemoveConnection, this, std::placeholders::_1));
        
        // 启动超时销毁功能
        if(_enable_inactive_release)
            conn->EnableInactiveRelease(10); 
        conn->Established();             // 就绪初始化

        _conns.insert(std::make_pair(_next_id, conn));
    }
    void RemoveConnectionInLoop(const PtrConnection &conn)
    {
        int id = conn->ConnectionId();
        _conns.erase(id);
    }
    // 从哈希map中移除连接信息
    void RemoveConnection(const PtrConnection &conn)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
    }

    void RunAfterInLoop(const TaskFunc &task, int delay)
    {
        _next_id++;
        _baseloop.TimerAdd(_next_id, delay, task);
    }

public:
    TcpServer(int port) : _port(port), _next_id(0), _enable_inactive_release(false), _acceptor(&_baseloop, port), _pool(&_baseloop)
    {
        // 创建从属线程
        _pool.CreateCountReactor();
        // 将监听套接字挂到baseloop上
        _acceptor.Listen();
    }

    void SetThreadCount(int count) { return _pool.SetThreadCount(count); }
    void SetConnectionCallback(const ConnectionCallback &cb) { _connection_callback = cb; }
    void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
    void SetCloseCallback(const CloseCallback &cb) { _closed_callback = cb; }
    void SetAnyEventCallback(const AnyEventCallback &cb) { _anyevent_callback = cb; }

    void EnableInactiveRelease(int timeout)
    {
        _timeout = timeout;
        _enable_inactive_release = true;
    }
    // 添加一个定时任务
    void RunAfter(const TaskFunc &task, int delay)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, task, delay));
    }
    void Start()
    {
        _baseloop.Start();
    }
};

class NetWork
{
public:
    NetWork()
    {
        signal(SIGPIPE, SIG_IGN);
    }
};
static NetWork nw;